import { defineStore } from 'pinia'
import { getDynamicMenus } from '@/router/helper/utils'
import { AUTH_STORE_NAME } from '../const'

export default defineStore(AUTH_STORE_NAME, () => {
  const authMenuList = ref([])

  const menuList = computed(() => authMenuList.value)
  const fltMenus = computed(() => _filterAuthMenuList(authMenuList.value))

  async function getAuthMenuList() {
    const menus = await getDynamicMenus()
    // const fltMenus = filterAuthMenuList(menus)
    authMenuList.value = _addDefaultIcon(menus)

    return menus
  }

  function clearAuthMenuList() {
    authMenuList.value = []
  }

  // 隐藏authMenuList中meta.hidden为true的菜单
  function _filterAuthMenuList(menuList) {
    return menuList.filter((item) => {
      if (item.meta && item.meta.hidden) {
        return false
      }
      if (item.children) {
        item.children = _filterAuthMenuList(item.children)
      }
      return true
    })
  }

  // 为menus添加默认icon
  function _addDefaultIcon(menus) {
    return menus.map((item) => {
      const newRoute = {
        ...item,
        meta: {
          ...item.meta,
          icon: item.meta?.icon || 'ElementPlus',
        },
      }

      if (newRoute.children && newRoute.children.length > 0) {
        newRoute.children = _addDefaultIcon(newRoute.children)
      }

      return newRoute
    })
  }

  return {
    authMenuList,
    fltMenus,
    menuList,
    getAuthMenuList,
    clearAuthMenuList,
    _addDefaultIcon,
  }
})
